var mongoose = require('mongoose')
    Schema = mongoose.Schema;
var schema = new Schema({
    name: String,
    content: [mongoose.Schema.Types.ObjectId]
}),
    fn = schema.methods,
    modelFn = schema.statics;

modelFn.create = function(tag) {
    return new model({
        name: tag,
        content: []
    }).save();
}

modelFn.delete = function(_id) {
    return model.findById(_id).then(doc => {
        if (doc) {
            return doc.remove({
                _id: _id
            });
        } else {
            return Promise.reject(null);
        }
    })
    
}

modelFn.read = function(_id) {
    return model.findById(_id).exec();
}

modelFn.addImages = function(tag_id, [...image_ids]) {
    return model
        .findById(tag_id).exec()
        .then(function(doc) {
            doc.content.addToSet.apply(doc.content, image_ids);
            doc.markModified('content');
            return doc.save();
        })
}

modelFn.removeImages = function(_id, [...image_ids]) {
    return model
        .findById(_id).exec()
        .then(function(doc) {
            image_ids.forEach((image_id) => {
                var index = doc.content.indexOf(image_id);
                if (index != -1) {
                    doc.content.splice(index, 1);
                }
            });
            
            doc.markModified('content');
            return doc.save();
        })
}

modelFn.rename = function(_id, newName) {
    return model.findById(_id).exec()
    .then(function(doc) {
        doc.name = newName;
        doc.markModified('name');
        return doc.save();
    });
}

modelFn.listAll = function() {
    return model.find({}).exec();
}

var model = mongoose.model('tag', schema);
module.exports = model;